<!--
 * @Author: zyk
 * @Date: 2020-07-13 16:00:22
 * @Last Modified by:   lide1202@hotmail.com
 * @Last Modified time: 2021-04-16 16:00:22
!-->
<template>
  <div id="app">
    <router-view v-if="isRouterAlive" />
  </div>
</template>

<script>
import { eventBus } from '@/utils/eventBus'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default {
  name: 'App',
  provide() {
    return {
      reload: this.reload,
    }
  },
  data() {
    return {
      isRouterAlive: true,

      stompClient: {}, // socket全局客户端
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.openWebSocket()
  },
  beforeDestroy() {
    // 销毁监听
    this.closeWebSocket()
  },

  methods: {
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },
    // 发送事件
    fire(eventType, eventData) {
      eventBus.$emit(eventType, eventData)
    },
    // 打开websocket连接
    openWebSocket() {
      // 建立连接对象
      const socket = new SockJS(process.env.VUE_APP_BASE_API + '/auth/websocket')
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket)
      // 定义客户端的认证信息,按需求配置
      const headers = {
        Authorization: this.userToken,
      }
      const _this = this
      // 向服务器发起连接
      this.stompClient.connect(headers, (frame) => {
        console.log('openWebSocket')
        this.stompClient.subscribe('/user/' + _this.userName + '/message', function(sokcetResponse) {
          /*
          {
          "id":"136",
          "title":"test adfasdfmsg0sdfadfsdf09",
          "time":"2021-04-16 15:43:39",
          "eventData":"{\"id\":11,\"name\":\"nini\",\"time\":\"2020-09-08\"}",
          "eventType":"EVENT_TYPE_SYSTEM_MSG"
          }
          */
          if (sokcetResponse == null || sokcetResponse.body == null) {
            return
          }
          var response = JSON.parse(sokcetResponse.body)
          _this.fire(response.eventType, response)

          // 根据eventType不同，开发人员可以自定义不同type的处理逻辑
          // eventBus.$on(eventType, (response) => {})
        })
      })
    },
    // 断开连接
    closeWebSocket() {
      if (this.stompClient !== null) {
        this.stompClient.disconnect()
      }
      console.log('closeWebSocket')
    },
  },
}
</script>
